﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyExe.Help
{
    public class IniParser
    {
        private Dictionary<string, Dictionary<string, string>> _data = new Dictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase);
        private string _filePath;

        public IniParser(string filePath)
        {
            _filePath = filePath;
            ParseFile();
        }

        private void ParseFile()
        {
            if (!File.Exists(_filePath))
                throw new FileNotFoundException($"INI文件未找到: {_filePath}");

            string currentSection = null;

            foreach (string line in File.ReadAllLines(_filePath))
            {
                string trimmedLine = line.Trim();

                // 跳过空行和注释
                if (string.IsNullOrEmpty(trimmedLine) || trimmedLine.StartsWith(";") || trimmedLine.StartsWith("#"))
                    continue;

                // 处理节
                if (trimmedLine.StartsWith("[") && trimmedLine.EndsWith("]"))
                {
                    currentSection = trimmedLine.Substring(1, trimmedLine.Length - 2);
                    if (!_data.ContainsKey(currentSection))
                    {
                        _data[currentSection] = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                    }
                    continue;
                }

                // 处理键值对
                int separatorIndex = trimmedLine.IndexOf('=');
                if (separatorIndex > 0 && currentSection != null)
                {
                    string key = trimmedLine.Substring(0, separatorIndex).Trim();
                    string value = trimmedLine.Substring(separatorIndex + 1).Trim();
                    _data[currentSection][key] = value;
                }
            }
        }

        public string GetValue(string section, string key, string defaultValue = null)
        {
            if (_data.TryGetValue(section, out var sectionData) && sectionData.TryGetValue(key, out var value))
            {
                return value;
            }
            return defaultValue;
        }
    }
}
